#include "counter.h"
#include "key.h"
#include "stdio.h"

uint16_t counter_count_old = 0;
TIM_HandleTypeDef counter_handle = {0};

void counter_init(uint16_t arr, uint16_t psc)
{
    TIM_SlaveConfigTypeDef slave_config = {0};
    
    counter_handle.Instance = TIM2;
    counter_handle.Init.Prescaler = psc;
    counter_handle.Init.Period = arr;
    counter_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
    counter_handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    
    slave_config.SlaveMode = TIM_SLAVEMODE_EXTERNAL1;
    slave_config.TriggerPolarity = TIM_TRIGGERPOLARITY_FALLING;
    slave_config.TriggerPrescaler = TIM_TRIGGERPRESCALER_DIV1;
    slave_config.TriggerFilter = 0;
    slave_config.InputTrigger = TIM_TS_TI2FP2;
    
    HAL_TIM_IC_Init(&counter_handle);
    HAL_TIM_SlaveConfigSynchro(&counter_handle, &slave_config);
    HAL_TIM_IC_Start(&counter_handle, TIM_CHANNEL_2);
    
}

void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
{
    if (htim->Instance != TIM2)
        return ;
    
    __HAL_RCC_TIM2_CLK_ENABLE();
    key_init();
}

uint16_t get_counter_count(void)
{
    if (counter_count_old == __HAL_TIM_GET_COUNTER(&counter_handle))
        return 0;
    
    counter_count_old = __HAL_TIM_GET_COUNTER(&counter_handle);
    printf("press count : %d\r\n", counter_count_old);
    return counter_count_old;
}



